<template>
    <div class="p-15 p-t-0">
        <div class="table-padding orderDialog">
            <el-form :model="modelForm" ref="modelForm" >
                <div>
                  <el-row :gutter="24">
                    <el-col :span="8">
                      <el-form-item prop="supplier" :rules="[]">
                        <div class="el-input el-input-group el-input-group--prepend">
                          <div class="el-input-group__prepend">供应商{{supplierDis}}</div>
                          <el-select v-model="modelForm.supplierId" :disabled="isEdit || supplierDis" filterable placeholder="请选择供应商" size="medium"
                                     class="w-100p">
                            <el-option
                              v-for="item in suppliers"
                              :key="item.id"
                              :label="item.name"
                              :disabled="item.state && item.state.key!='NORMAL' "
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="warehouse" :rules="[]">
                        <div class="el-input el-input-group el-input-group--prepend">
                          <div class="el-input-group__prepend">出库仓库</div>
                          <el-select v-model="modelForm.warehouseId" placeholder="请选择出库仓库" :disabled="isEdit" class="w-100p" size="medium">
                            <el-option
                              v-for="item in warehouses"
                              :key="item.id"
                              :disabled="item.state&& item.state.key!='NORMAL'"
                              :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8" >
                      <el-form-item prop="createAt" :rules="[]">
                        <div class="el-input el-input-group el-input-group--prepend">
                          <div class="el-input-group__prepend">出库日期</div>
                          <el-date-picker
                            v-model="modelForm.outTime"
                            type="date"
                            class="w-100p"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            :readonly="true"
                            placeholder="出库日期" >
                          </el-date-picker>
                        </div>
                      </el-form-item>
                    </el-col>

                  </el-row>

                  <el-row :gutter="24">
                    <el-col :span="8">
                      <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium">
                        <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                          <span>单据类型</span>
                        </div>
                        <el-select v-model="modelForm.type" placeholder="请选择单据类型" :disabled="isEdit" class="w-100p" size="medium" @change="changeType">
                          <el-option
                            v-for="item in StoreOutType"
                            :key="item.key"
                            :label="item.text"
                            :value="item.key">
                          </el-option>
                        </el-select>
                        <br>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item  prop="supplier" :rules="[]" >
                        <div class="el-input el-input-group el-input-group--prepend">
                          <div class="el-input-group__prepend">商品信息库</div>
                          <el-select v-model="modelForm.storeId" @change="storeChange" filterable placeholder="请选择商品信息库" :disabled="isEdit" style="width: 100%">
                            <el-option
                              v-for="item in storeList"
                              :key="item.id"
                              :label="item.name"
                              :disabled="item.state!='NORMAL'"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="no" :rules="[]">
                        <el-input type="text" v-model="modelForm.remark" size="medium"
                                  auto-complete="off"
                                  class="w-100p"
                                  :disabled="isEdit"
                                  placeholder="请输入备注信息">
                          <template slot="prepend">
                            <el-button>备注</el-button>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
                <div >
                  <div class="text-left" style="color:red">注:请先选择仓库后在选原料</div>
                    <el-form-item class="text-left text-left1">
                        <el-button type="primary"  size="medium" @click="submitForm('modelForm')"><i class="icon icon-baocun"></i> 保存</el-button>
                        <el-button class="m-l-0"  size="medium" type="success" @click="resetForm('modelForm')"><i class="icon icon-tijiao"></i> 提交并审核</el-button>
                        <!--<el-button type="warning"  size="medium" v-if="modelForm.id" @click="printOrder"><i class="icon icon-dayin"></i> 打印</el-button>-->
                        <el-button type="danger"  size="medium" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
                    </el-form-item>
                    <el-form-item class="text-left text-left5">
                        <el-button type="warning"  size="medium" @click="printOrder"><i class="icon icon-dayin"></i> 打印</el-button>
                        <el-button type="danger"  size="medium" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
                    </el-form-item>
                  <div class="orderTable">

                    <el-table
                            :data="tableData"
                            border
                            show-summary
                            :summary-method="getSummaries"
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                width="50">
                        </el-table-column>
                        <el-table-column
                                width="80">
                            <template  slot-scope="scope">
                                <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addColumn(scope.$index)"></span>
                                <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusColumn(scope.$index)"></span>
                            </template>
                        </el-table-column>
                      <el-table-column
                        prop="code"
                        label="编号"
                        width="150">
                        <template  slot-scope="scope">
                          <div style="position: relative">
                            <el-select class="codeNo" :class="'coderef_'+scope.$index"
                                       :ref="'coderef_'+scope.$index" v-model="scope.row.code" :disabled="isEdit" remote @change="codeChange(scope.$index)"
                                       :remote-method="remoteMethod"  :loading="loading"  @focus="codeFocus" filterable=""
                                        placeholder="编号/条码/名称/简码" @keyup.enter.native="codeEnter($event,scope.$index)">
                              <el-option :disabled="true" value="0000" style="background-color: #409EFF;color: #fff;">
                                <div style="width:600px;" >
                                  <el-row>
                                    <el-col :span="4">编号</el-col>
                                    <el-col :span="7">条码</el-col>
                                    <el-col :span="7">名称</el-col>
                                    <el-col :span="3">库存单位</el-col>
                                    <el-col :span="3">库存数量</el-col>
                                  </el-row>
                                </div>
                              </el-option>
                              <el-option v-for="(item,index) in material" :disabled="(item.state && item.state!='NORMAL')" :key="index"
                                         :label="item.material_no" :value="item.material_no" >
                                <div style="width:600px;border-bottom:1px solid #c0c0c0;padding:5px 0px">
                                  <!--{{item.value}}[{{item.purchaseUnit}}]-->
                                  <el-row>
                                    <el-col :span="4"><span v-if="item.material_no">{{item.material_no}}</span><span v-else>-</span></el-col>
                                    <el-col :span="7"><span v-if="item.goodcode">{{item.goodcode}}</span><span v-else>-</span></el-col>
                                    <el-col :span="7"><span v-if="item.matrial_name">{{item.matrial_name}}</span><span v-else>-</span></el-col>
                                    <el-col :span="3"><span v-if="item.material_unit">{{item.material_unit}}</span><span v-else>-</span></el-col>
                                    <el-col :span="3"><span v-if="item.count">{{item.count}}</span><span v-else>-</span></el-col>
                                  </el-row>
                                </div>
                              </el-option>
                            </el-select>

                            <span class="el-icon-more" @click="handleIconClick(scope.$index)"
                                  style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="goodcode"
                        label="条码">
                        <template  slot-scope="scope">
                          <el-tooltip class="item" effect="light" placement="bottom-start" v-if="scope.row.goodcodes && scope.row.goodcodes.length>1">
                            <div slot="content">所选品项含有多个条码:<br/>
                              <div v-for="(item,index) in scope.row.goodcodes">
                                <span>{{index+1}}、{{item}}</span>
                              </div>
                            </div>
                            <el-button  type="text" style="padding-top: 0; padding-bottom: 0">{{scope.row.goodcode}}</el-button>
                          </el-tooltip>
                          <span v-else>{{scope.row.goodcode}}</span><br />
                        </template>
                      </el-table-column>
                        <el-table-column
                                prop="name"
                                label="名称"
                                width="250" >
                        </el-table-column>
                        <el-table-column
                                prop="spec"
                                label="规格型号"
                                >
                        </el-table-column>
                        <!--<el-table-column-->
                                <!--prop="purchaseSpec"-->
                                <!--label="采购规格"-->
                                <!--width="100">-->
                        <!--</el-table-column>-->
                        <el-table-column
                                prop="unitName"
                                label="库存单位"
                                width="100">
                        </el-table-column>
                        <el-table-column
                                prop="count"
                                label="数量"
                                width="150">
                            <template  slot-scope="scope">
                                <el-input v-model="scope.row.count"
                                          :disabled="isEdit" @blur="priceValidate(scope.row,'count');calcStock(scope.$index,scope.row)"
                                          @focus="printNum()"  placeholder="0.00"
                                          :class="'focus_input_'+scope.$index"
                                          @keyup.enter.native="nextFocus(scope.$index,'remark_focus_')"
                                ></el-input>
                            </template>
                        </el-table-column>
                        <!--<el-table-column-->
                                <!--prop="price"-->
                                <!--label="采购单价"-->
                                <!--width="150">-->
                            <!--<template  slot-scope="scope">-->
                                <!--<el-input v-model="scope.row.price" :disabled="isEdit" @blur="priceValidate(scope.row,'price')"  placeholder="0.00"></el-input>-->
                            <!--</template>-->
                        <!--</el-table-column>-->
                        <el-table-column v-if="!this.isEdit"
                                prop="stockCount"
                                label="库存"
                                width="150">
                            <template  slot-scope="scope">
                                <span>{{scope.row.stockCount  | money}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="cost"
                                label="库存单价"
                                width="150">
                            <template  slot-scope="scope">
                              <span>{{scope.row.cost | money}}</span>
                            </template>
                        </el-table-column>


                      <el-table-column
                        prop="chuKuPrice"
                        label="出库单价"
                        width="150">
                        <template  slot-scope="scope">
                          <el-input v-model="scope.row.chuKuPrice" :disabled="isEdit" @focus="printNum()"  placeholder="0.00"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="this.isEdit"
                        prop="cost"
                        label="金额"
                        width="150">
                        <template  slot-scope="scope">
                          <span>{{scope.row.total | money}}</span>
                        </template>
                      </el-table-column>
                        <el-table-column
                                prop="memo"
                                label="备注">
                            <template  slot-scope="scope">
                                <el-input v-model="scope.row.memo" :disabled="isEdit" :class="'remark_focus_'+scope.$index" @keyup.enter.native="nextFocus(scope.$index,'')" placeholder=""></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                  </div>
                  <el-row style="margin-top: 15px" class="text-left" v-if="modelForm.supplierId">
                    <el-col :span="8">
                      <el-input type="text" style="width:80%" size="medium" :disabled="true" v-model="sumOrderPrice" auto-complete="off" placeholder="请输入本单优惠金额">
                        <template slot="prepend">
                          <el-button>总金额</el-button>
                        </template>
                      </el-input>
                    </el-col>
                    <!--<el-col :span="8">-->
                      <!--<el-input type="text" style="width:80%"  size="medium" v-model="modelForm.giftAmount" :disabled="isEdit" auto-complete="off"   @focus="printNum()"   @blur="isDouble(modelForm,'giftAmount');calcPrice()"-->
                                <!--placeholder="优惠金额">-->
                        <!--<template slot="prepend">-->
                          <!--<el-button>优惠金额</el-button>-->
                        <!--</template>-->
                      <!--</el-input>-->
                    <!--</el-col>-->
                    <el-col :span="8">
                      <el-input type="text" style="width:80%"  size="medium" v-model="modelForm.payAmount" :disabled="isEdit" auto-complete="off"  @focus="printNum()"  @blur="isDouble(modelForm,'payAmount');calcPrice()"
                                placeholder="实付款金额">
                        <template slot="prepend">
                          <el-button>实付款金额</el-button>
                        </template>
                      </el-input>
                    </el-col>
                  </el-row>
                </div>
            </el-form>

        </div>
      <materials-select :isShow="dialogTableVisible"  :storeId="modelForm.storeId" :warehouseId="modelForm.warehouseId" v-on:pushData="getData" v-on:closeDialog="dialogTableVisible=false"></materials-select>
    </div>
</template>
<script>
  import materialsSelect from "@/components/outMaterialsSelect.vue"
    //注意路径
    export default{
        data(){
            return {
                sumOrderPrice:0,
                dialogTableVisible:false,
                isEdit:false,
                tableData: [{
                    id:"",
                    code: '',
                    name: '',
                    goodsSpec: '',
                    purchaseSpec: '',
                    unitName:'',
                    count:'0',
                    price:'0.00',
                    historyPrice:'',
                    money:'0.00',
                    memo:'',
                }],
                modelForm: {
                  warehouseId:""
                },

                pageSizeSet:window.pageSizes,
                pageSize:window.pageSize,
                pageTotal:10,
                material:[],
                supplier:"",
                content:"",
                warehouse:"",
                suppliers:[],
                warehouses:[],
              StoreOutType:[],
                restaurants: [],
                timeout:  null,
                gridData: [ ],
                itemActive:0,
                data: [],
                selectRow:[],
                inputText:"",
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
              storeList:[],
              query:"",
              loading:false,
              oldGoodStoreId:"", //切换之前的商品库
              supplierDis:false
            }
        },
        created(){
            window.this = this;
            window.isload=true;
           this.initData();
        },
      components: {
        materialsSelect
      },
        mounted(){
            if(this.$route.query.type!=null && this.$route.query.type!=""){
                if(this.$route.query.type=="5"){//5 说明是查看
                    $("input").attr("disabled", true);
                    $(".text-left1").css("display","none");
                    $(".text-left5").css("display","block");
                    this.isEdit=true;
                }
            }
        },
        methods: {
          changeType(){
            console.log(this.modelForm.type);
            if(this.modelForm.type!='STOREOUT'){
              this.supplierDis=true;
              this.modelForm.supplierId='';

            }else{
              this.supplierDis=false;
            }
          },
          calcPrice(){
            var sum=Number(this.sumOrderPrice);
            var discount=Number(this.modelForm.giftAmount);
            var recharge=Number(this.modelForm.payAmount);
            if(discount>sum){
              this.$message.error("优惠金额不能大于总金额");
              this.modelForm.giftAmount=0.00;
              return false;

            }
            if(recharge>sum){
              this.$message.error("实付金额不能大于总金额");
              this.modelForm.payAmount=0.00;
              return false;
            }
            if((discount+recharge)>sum){
              this.$message.error("输入金额有误，请重新核对");
              this.modelForm.giftAmount=0.00;
              this.modelForm.payAmount=0.00;
              return false;
            }
          },
          isDouble(item,key){
            // var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            var isNum=/^\d+(\.{0,1}\d+){0,1}$/
            if(!isNum.test(item[key])){
              item[key]="0.00"
            }else{
              item[key]=item[key]
            }
          },
          nextFocus(index,name){
            if(name){
              $("."+name+index+" input").focus();
            }else {
              $(".coderef_"+(index+1)+" input").focus();

            }
          },
          storeChange(){
            this.material = [];
            if(this.tableData && this.tableData.length>0 && this.tableData[0].id !=''){
              this.$confirm('切换商品信息库将清除已选择的物品信息?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.tableData = [{
                  id:"",
                  code: '',
                  name: '',
                  goodsSpec: '',
                  purchaseSpec: '',
                  unitName:'',
                  count:'0',
                  price:'0.00',
                  historyPrice:'',
                  money:'0.00',
                  memo:'',
                }];
              }).catch(() => {

              });
            }
          },
          calcStock(index,row){
            console.log(index,row);
            if(row.count*1>row.stockCount){
              this.$message.error("商品"+row.name+"的数量超过了库存数量");
              this.tableData[index].count='0.00';
            }
          },
          printNum(){
            event.currentTarget.select();
          },
          priceValidate(item, key) {
            console.log("(((((((((((");
            console.log(item[key]);
            var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if (!isNum.test(item[key])) {
              item[key] = "0.00"
            } else {
              item[key] = item[key]
            }
            switch (key) {
              case "count":
                if (!isNaN(item.count)) {
                  item.money = item.price * item.count;
                  item.money = item.money.toFixed(2);
                } else {
                  item.count = 0
                }
                break;
              case "price":
                if (!isNaN(item.price)) {
                  item.money = item.price * item.count;
                  item.money = item.money.toFixed(2);
                  item.price = (item.price * 1).toFixed(2);
                } else {
                  item.price = '0.00';
                }
                break;
              case "money":
                if (!isNaN(item.money) && item.count > 0) {
                  item.price = item.money / item.count;
                  item.price = item.price.toFixed(2);
                  item.money = (item.money * 1).toFixed(2);
                } else {
                  item.money = '0.00';
                }
                break;
              case 'chuKuPrice':
                if (!isNaN(item.chuKuPrice) && item.count > 0) {
                  item.price = item.money / item.count;
                  item.price = item.price.toFixed(2);
                  item.money = (item.money * 1).toFixed(2);
                } else {
                  item.money = '0.00';
                }
                break;
            }
          },
          calcAmount(){

          },
          codeEnter(e,index){
            console.log(">>>>>>>>>>>>>>>>codeEnter>");
            console.log(e);
            if(e && e.target && e.target.value){
              this.$axios.get("materials/materials/getMaterialsByNameOrCodeForOut?page.pn=0&page.size=15&storeId="+this.modelForm.storeId+"&keywords="+e.target.value+"&warehouseId="+this.modelForm.warehouseId).then(data=>{
                this.loading = false;
                if(data.status==200){
                  this.material=data.content.materials.content;
                  this.$refs['coderef_'+index].blur();
                  if(e && this.material.length<=0){
                    e.target.select();
                    return;
                  }
                  this.codeForTable(index);
                  if(!this.tableData[index+1]){
                    this.addColumn(index);
                  }
                  this.material=[];
                  setTimeout(function () {
                    $(".focus_input_"+index+" input").focus();
                  },300);
                }
              });
            }else {
              return;
            }
          },
          codeForTable(index) {
            console.log("fffffffffffffffff");
            if(this.material && this.material.length>0){
              if(this.tableData && this.tableData.length>0){
                for (var m = 0; m < this.tableData.length; m++) {
                  if (m!=index && this.material[0].material_id == this.tableData[m].id) {
                    this.$message.info("您本次添加的["+this.tableData[m].code+"]品项含有重复");
                    break;
                  }
                }
              }
              console.log("<<<<<<<<<<>>>>>>>");
              console.log(this.material);
              this.tableData[index].id = this.material[0].material_id;
              this.tableData[index].name = this.material[0].matrial_name;
              this.tableData[index].code = this.material[0].material_no;
              this.tableData[index].spec = this.material[0].goods_spec;
              this.tableData[index].unitName = this.material[0].material_unit;
              this.tableData[index].stockCount = this.material[0].count;
              this.tableData[index].amount = this.material[0].amount;
              this.tableData[index].cost = this.material[0].cost;
              this.tableData[index].chuKuPrice=0.00;
              this.tableData[index].goodcode = this.material[0].goodcode;
              this.tableData[index].goodcodes = this.material[0].goodcodes;
              this.tableData[index].goodcodestrs = this.material[0].codes;
            }
            this.material=[];
          },

          codeChange(index) {
            for (var i = 0; i < this.material.length; i++) {
              if (this.material[i].material_no === this.tableData[index].code) {
                for (var m = 0; m < this.tableData.length; m++) {
                  if (this.material[i].material_id == this.tableData[m].id) {
                    this.$message.info("本次添加含有重复原料");
                    break;
                  }
                }
                this.tableData[index].id = this.material[i].material_id;
                this.tableData[index].name = this.material[i].matrial_name;
                this.tableData[index].code = this.material[i].material_no;
                this.tableData[index].spec = this.material[i].goods_spec;
                this.tableData[index].unitName = this.material[i].material_unit;
                this.tableData[index].stockCount = this.material[i].count;
                this.tableData[index].amount = this.material[i].amount;
                this.tableData[index].cost = this.material[i].cost;
                this.tableData[index].chuKuPrice=0.00;
                this.tableData[index].goodcode = this.material[i].goodcode;
                this.tableData[index].goodcodes = this.material[i].goodcodes;
                this.tableData[index].goodcodestrs = this.material[i].codes;
                this.material = [];
                break;
              }
            }
          },
          remoteMethod(query) {
            console.log("query >>> : ",query);
            if(this.modelForm.warehouseId=="" || this.modelForm.warehouseId==null ){
              this.$message.error("请先选择仓库");
              return;
            }
            if(!this.modelForm.storeId){
              this.$message({
                message: '请选择商品信息库',
                type: 'warning'
              });
              return;
            }
            if(query) {
              this.loading = true;
              this.$axios.get("materials/materials/getMaterialsByNameOrCodeForOut?page.pn=0&page.size=15&storeId="+this.modelForm.storeId+"&keywords="+query+"&warehouseId="+this.modelForm.warehouseId).then(data=>{
                this.loading = false;
                if(data.status==200){
                  this.material=data.content.materials.content;
                }
              });
            }else {
              this.material=[];
            }
          },
          codeFocus(){
            this.material=[];
          },
          getData(data){
            if(!this.material){
              this.material = [];
            }
            var a=0;
            for(var i=0;i<data.length;i++){
//              a=0;

             /* for(let s=0;s<this.material.length;s++){
                if(this.material[s].id==data[i].material_id){
                  console.log("3");
                  a++;
                }
              }*/
             /* if(a<=0){
                console.log("u");
                data[i].value="["+data[i].material_no+"]"+data[i].matrial_name;
                this.material.push(data[i]);
              }*/
              this.tableData.push({
                id:data[i].material_id,
                code:data[i].material_no,
                name:data[i].matrial_name,
                spec:data[i].goods_spec,
                unitName:data[i].material_unit,
                count: '0',
                chuKuPrice:0.00,
                memo: '',
                amount:data[i].amount,
                cost:data[i].cost,
                stockCount:data[i].count,
                goodcode:data[i].goodcode,
                goodcodes:data[i].goodcodes,
                goodcodestrs:data[i].goodcodestrs,
              });
            }
            for(var i=0;i<this.tableData.length;i++){
              if(this.tableData[i].id==''){
                this.tableData.splice(i,1);
              }
            }
            this.material = [];
            this.dialogTableVisible=false;
          },
            //页面第一次进来获取表单需要的数据
            initData(){
                var id=this.$route.query.id;
                var query="";
                if(id!=null && id!=""){
                    query="?id="+id;
                    this.modelForm.id=id;
                }

                this.$axios.get("stores/storeOutOrders/create"+query).then(data=>{
                    if(data.status==200){
                        let json = data.content;
                        this.modelForm = json.storeOutOrder;
                        this.modelForm.outTime=this.moment().format("YYYY-MM-DD");
                        this.suppliers = json.suppliers;
                        this.warehouses = json.warehouses;
                        this.storeList = json.storeList;

                        // if(this.warehouses &&　this.warehouses.length>0){
                        //   this.modelForm.warehouseId=this.warehouses[0].id;
                        // }
                      for(var i=0;i<json.StoreOutType.length;i++){
                        this.StoreOutType.push(json.StoreOutType[i]);
                        if(i==2 && this.$route.query.type!=5){
                          break;
                        }
                      }
                        // this.StoreOutType=json.StoreOutType;
                      if (id != null && id != "") {
//                        this.material=json.materials;
                        for (var i = 0; i < json.detailList.length; i++) {
                          for(var j=0;j<json.materials.length;j++){
                            if(json.detailList[i].materialId==json.materials[j].material_id){
                              json.detailList[i].stockCount=json.materials[j].count;
                              json.detailList[i].cost=json.materials[i].cost;
                            }
                          }
                          json.detailList[i].price = (json.detailList[i].price * 1).toFixed(2);
                          json.detailList[i].unitName = json.detailList[i].unit;
                          json.detailList[i].spec = json.detailList[i].spec;
                          json.detailList[i].id = json.detailList[i].materialId ;
                          json.detailList[i].name = json.detailList[i].name ;
                          json.detailList[i].memo = json.detailList[i].remark ;
                          if(this.modelForm.type=='OTHEROUT'){
                            json.detailList[i].chuKuPrice=json.detailList[i].price;
                          }

                          if(json.detailList[i].code && json.detailList[i].code!=''){
                            if(json.detailList[i].code.indexOf(","+this.query+",")!=-1){
                              json.detailList[i].goodcode = this.query;
                            }else {
                              json.detailList[i].goodcode = json.detailList[i].code.substring(1,this.tableData[i].codes.indexOf(",",2));
                            }
                            json.detailList[i].code = json.detailList[i].code.substring(1,json.detailList[i].code.length-2);
                            if(json.detailList[i].code!=''){
                              json.detailList[i].goodcodes = json.detailList[i].code.split(",");
                            }
                          }else{
                            json.detailList[i].goodcode="";
                            json.detailList[i].goodcodes=[];
                          }
                          json.detailList[i].goodcodestrs = json.detailList[i].code;
                          json.detailList[i].code = json.detailList[i].no;
                        }
                        this.tableData = json.detailList;
                        this.material = [];
                      }
                    }else{
                        this.$message.error(data.message);
                    }
                })
            },
            checkboxInit(row,index){
                console.log(row.state.key);
                if(row.state && row.state.key!="NORMAL"){
                    return 0;//不可勾选
                }else{
                    return 1;
                }
            },
            /* 打印单据 */
            printOrder(){
                // 打印预览
                var $this=this;
                setTimeout(function(){
                    $this.Print($this.$refs.printData);
                }, 200);
            },
            handleIconClick(index){
              if(!this.modelForm.storeId){
                this.$message({
                  message: '请选择商品信息库',
                  type: 'warning'
                });
                return;
              }
                if(this.isEdit) {
                   return;
                }
                if(this.modelForm.warehouseId=='' || this.modelForm.warehouseId==null){
                  this.$message.error("请先选择仓库");
                  return;
                }
                this.dialogTableVisible = true;
                this.itemActive = index;
            },
          selectGood(page) {
            this.dialogTableVisible = true;
          },
            handleSizeChange(val){
                this.pageSize=val;
            },
            handleNodeClick(data) {
                var id=data.id;
                this.selectGood("");
            },
            goBack() {
                this.router.go(-1);
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    if(index==7 || index==10){
                        const values = data.map(item => Number(item[column.property]));
                        if (!values.every(value => isNaN(value))) {
                            sums[index] = values.reduce((prev, curr) => {
                                const value = Number(curr);
                                if (!isNaN(value)) {
                                    if(index==7 ){
                                        return prev + curr;
                                    }else if(index==10){
                                      return prev + curr;
                                    }else{
                                        return ((prev*1 + curr*1)*1).toFixed(2);
                                    }
                                } else {
                                    if(index==6 ){
                                        return prev;
                                    }else{
                                        return (prev*1).toFixed(2);
                                    }

                                }
                            }, 0);
                        } else {
                            sums[index] = 0;
                        }
                    }
                });
                if(sums[7]!=0 && sums[7]!=undefined && sums[10]!=0 && sums[10]!=undefined){
                  console.log("KKKKKK");
                  this.sumOrderPrice=sums[7]*sums[10];
                }
          return sums;
            },
            submitForm(formName) {
                //console.log(this.tableData)
                this.type=1;
                this.validateData(formName);
            },
            resetForm(formName) {
                this.type=2;
                this.validateData(formName);
            },
            validateData(fromName){
                if (this.modelForm.warehouseId == null) {
                    this.$message.error("请选择仓库！");
                    return;
                }
                if (this.modelForm.type=='STOREOUT'&& this.modelForm.supplierId == null) {
                    this.$message.error("请选择供应商！");
                    return;
                }
                if(this.modelForm.type==null){
                  this.$message.error("请选择单据类型");
                  return ;
                }

                for (var i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].id == "") {
                        if (this.tableData.length == 1) {
                            this.$message.error("请添加单据明细！");
                            return;
                        }
                        this.tableData.splice(i, 1);
                        i--;
                    }
                    if(this.modelForm.type){
                        if (this.tableData[i].count <= 0) {
                            this.$message.error("数量不能小于1！请检查第"+(i+1)+"行数据");
                            return;
                        }
                        if(this.tableData[i].count>this.tableData[i].stockCount){
                          this.$message.error("商品"+this.tableData[i].name+"的数量超出了库存数量");
                          return;
                        }
                    }
                }
                if (this.tableData == null || this.tableData.length == 0) {
                    this.$message.error("请添加单据明细！");
                    return;
                }
                if(this.$route.query.type=="4") {//5 说明是查看
                    this.modelForm.id="";
                }
                this.$refs[fromName].validate((valid)=> {
                    if (valid) {
                        var data = {};
                        data.storeOutOrder = this.modelForm;
                      data.type=this.type;
                      for(let i=0;i<this.suppliers.length;i++){
                        if( this.modelForm.supplierId==this.suppliers[i].id){
                          this.modelForm.supplierName=this.suppliers[i].name;
                        }
                      }
                      for(let i=0;i<this.warehouses.length;i++){
                        if( this.modelForm.warehouseId==this.warehouses[i].id){
                          this.modelForm.warehouseName=this.warehouses[i].name;
                        }
                      }
                        var tempData=[];
                      console.log(this.modelForm.type);
                        for(var i=0;i<this.tableData.length;i++){
                          var price="";
                          if(this.modelForm.type=='OTHEROUT'){
                            price=this.tableData[i].chuKuPrice;
                          }else{
                            price=this.tableData[i].cost;
                          }
                          console.log(this.tableData[i]);
                          tempData.push({
                            materialId:this.tableData[i].id,
                            name:this.tableData[i].name,
                            no:this.tableData[i].code,
                            spec:this.tableData[i].spec,
                            unit:this.tableData[i].unitName,
                            count:this.tableData[i].count,
                            price:price,
                            remark:this.tableData[i].memo
                          })
                        }
                        data.details = tempData;
                        // data = JSON.stringify(data);
                        //console.log(data)
                        this.$axios.post("stores/storeOutOrders/create", data, "json").then(data=> {
                            if (data.status == 200) {
                                this.$message({
                                    message: data.message,
                                    type: 'success'
                                });
                                this.$emit('addSuccess');
                                this.router.push({path:"/inventoryOutOrders"});
                            } else {
                                this.$message.error(data.message);
                            }
                        })
                    } else {
                        this.$message.error("请检查输入项");
                        return false;
                    }
                });
            },
            addColumn(index){
                if(this.isEdit) {
                    return;
                }
                this.tableData.splice(index+1,0,{
                    id:'',
                    code: '',
                    name: '',
                  spec: '',
                    unitName:'',
                    count:'0',
                    price:'0.00',
                  stockCount:'',
                  cost:'0.00',
                    memo:'',
                  chuKuPrice:"0.00"
                })
            },
            minusColumn(index){
                if(this.isEdit) {
                    return;
                }
                if(this.tableData.length>1){
                    this.tableData.splice(index,1);
                }else{
                    this.$message.info("最少保留一条");
                }
            },

        },

    }
</script>
<style scoped>
    .el-form-item{
        margin-bottom: 10px !important;
    }
    .el-table tr{
        border-bottom: 1px solid #dfe6ec !important;
    }
    .text-left5{display: none;}

    /*单据打印*/
    :root{
        --zoomsize: 60%;
        --line-height-set: 30px;
    }

    .print-con{zoom:60%; width:98%; color:#333333; font-size:12px !important; background-color: #ffffff; padding:0 10px; position: absolute; left: 0; top:0; z-index: -10;}

    /*单据-标题*/
    .print-con .order-title{zoom:var(--zoomsize); font-size: 12px; font-weight: bold; text-align: center; padding: 5px; border-bottom: 2px solid #333333; }

    /*单据-说明信息*/
    .print-con .order-info{padding:0; font-size: 10px !important; height: auto; overflow: hidden;}
    .print-con .order-info ul{height:auto; overflow: hidden; margin:0; padding:0; }
    .print-con .order-info ul li{list-style: none; font-size:12px;}
    .print-con .order-info ul li{zoom:var(--zoomsize); float:left; width:33%; height:var(--line-height-set); line-height: var(--line-height-set); overflow: hidden;}
    .print-con .order-info ul li.sigle-line{zoom:var(--zoomsize); width:100%; display: block;}

    /*单据-商品列表*/
    .print-con .tb-con{widht:100%; background-color: #b4b4b4; border: 1px solid #b4b4b4;}
    .print-con .tb-con th{zoom:var(--zoomsize); height:var(--line-height-set); line-height: var(--line-height-set); background-color: #ffffff; border: 1px solid #b4b4b4; font-size: 12px;}
    .print-con .tb-con td{zoom:var(--zoomsize); height:var(--line-height-set); line-height: var(--line-height-set); text-align: center; background-color: #ffffff; /*border: 1px solid #b4b4b4;*/ font-size: 12px;}

    /*责任条款*/
    .print-con .item-info{}
    .print-con .item-info ul{margin:0; padding:0; list-style: none;}
    .print-con .item-info ul li{zoom:var(--zoomsize); height:var(--line-height-set); line-height: var(--line-height-set); font-size: 12px;}

</style>
